# -*- coding:utf-8 -*-
__author__ = 'weikai'
from request_pingan.login import Login
from renewal import is_renewal,quickSearchVoucher
from DMVehicleInfo import queryDMVehicleInfoConfirm
import json
from request_cic.utils import getlatedate
from utils import compare_time40
from common import config
from common.MqSend import send_mq
import traceback
from carModelQuery import query_carmodel,queryAutoModelType
from pingan_feebody import get_fee
from request_pingan.log import Logger
from my_dbUtil.dbInsert import soupDb
from common import redisUtil
from  request_pingan.pinganRequestBody import get_pingan_redis_body
r=redisUtil.CRedis()
log=Logger()

#续保返回用户信息 如果无 则放回0
def is_pingan_renwal(session,plateNumber):
    try:
        if '-'not  in plateNumber:
            plateNumber=plateNumber[:2]+"-"+plateNumber[2:]

        if session =='' or session==None:
            login=Login()
            session=login.login()

        user_data=is_renewal(session,plateNumber)
        #续保用户
        if isinstance(user_data,dict):
            icorepnbs_session=user_data['request']
            quick_resp=quickSearchVoucher(icorepnbs_session,user_data)
            #获取车管所信息
            #session=quick_resp['request']
            #vehicleFrameNo=quick_resp['vehicleTarget']['vehicleFrameNo']
            #queryDMVehicleInfoConfirm_json=queryDMVehicleInfoConfirm(session,vehicleFrameNo,carMark="")
            #if queryDMVehicleInfoConfirm_json==0:
             #   log.error(u"车管所返回信息失败 %s " % plateNumber)
              #  return 0
            #如果商业险的结束时间为空那么取交强险的结束时间作为保险时间
            str_date=quick_resp['vehicleTarget']['firstRegisterDate']
            endDate=user_data.get("sy_insuranceEndTime","").split(" ")[0]
            if endDate=="":
                endDate=user_data.get("jq_insuranceEndTime","").split(" ")[0]

            out= {
          "licenseNo": user_data['vehicleLicenceCode'].replace('-',''),
          "vinNo": user_data['vehicleFrameNo'],
          "endDate": endDate,
          "CCardDetail": quick_resp['extendInfo']['ownerVehicleTypeCode'],
          "brandName": quick_resp['vehicleTarget']['modifyAutoModelName'],
          "insuredName": user_data['ownerName'],
          "identifyNumber": quick_resp.get("insurantInfo",{}).get("certificateTypeNo",""),
          "CUsageCde": "",
          "NNewPurchaseValue": "",
          "insuredAddress": "",
          "mobile": "",
          "enrollDate": str_date.split(" ")[0],#str_date[:4]+"-"+str_date[4:6]+"-"+str_date[6:],
          "engineNo": user_data['engineNo'],
          "CModelCde": user_data['makerModel'],
          "NSeatNum": quick_resp['vehicleTarget']['vehicleSeats'],
          "COMPANY_ID":"1"
        }
            return out
        else:
            log.info(u"未查询到续信息%s" % plateNumber)
            return 0
    except Exception ,e:
        log.error(e)
        log.error(traceback.format_exc())
        return 0




def pingan_request(session,renewal_data_dt):
    '''
    :param session:
    :param dt:
    :return:
    '''
    try:
        alldata={}
        insureCarId = renewal_data_dt.get('insureCarId','')
        CPlateNo = renewal_data_dt.get('plateNumber','')
        searchVin = renewal_data_dt.get('vinNo','')
        client=renewal_data_dt.get('client','')
        isPhone=renewal_data_dt['isPhone']
        sessionId=renewal_data_dt.get('sessionId','')
        endDate=renewal_data_dt.get('endDate','')
        insuranceType=renewal_data_dt.get("insuranceType",{})
        insureTypeGroupId=insuranceType.get("insuranceTypeGroupId","")
        insuranceTypeGroup=insuranceType.get("insuranceTypeGroup","")

        if endDate!="":
            min_time=compare_time40(endDate)
            if min_time > config.days:
                log.error("平安保险查询在40天内的 保险结束时间为 %s" % endDate)
                send_mq(client,CPlateNo,"平安保险查询在40天内的 保险结束时间为 %s" % endDate,"2","1",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)
                return "平安保险查询在40天内的 保险结束时间为 %s" % endDate
            if min_time < 0:
                endDate=getlatedate(1)

        #使用redis缓存进行查询
        re_out=get_pingan_redis_body(session,renewal_data_dt)
        if re_out==1:
            return

        if '-' not  in CPlateNo:
            plateNumber=CPlateNo[:2]+"-"+CPlateNo[2:]

        if session =='' or session==None:
            login=Login()
            session=login.login()

        #判断是否为续保用户
        user_data=is_renewal(session,plateNumber=plateNumber)
        if isinstance(user_data,dict):

            sy_insuranceEndTime=user_data.get("sy_insuranceEndTime","")
            jq_insuranceEndTime=user_data.get("jq_insuranceEndTime","")
            if sy_insuranceEndTime=="" and jq_insuranceEndTime!="" :
                sy_insuranceEndTime=jq_insuranceEndTime
            if sy_insuranceEndTime!="" and jq_insuranceEndTime=="" :
                jq_insuranceEndTime=sy_insuranceEndTime

            icorepnbs_session=user_data['request']
            quick_resp=quickSearchVoucher(icorepnbs_session,user_data)

            #获取车管所信息
            session=quick_resp['request']
            vehicleFrameNo=quick_resp['vehicleTarget']['vehicleFrameNo']

            queryDMVehicleInfoConfirm_json=queryDMVehicleInfoConfirm(session,vehicleFrameNo,carMark="")
            if not isinstance(queryDMVehicleInfoConfirm_json,dict):
                send_mq(client,CPlateNo,queryDMVehicleInfoConfirm_json,"2","1",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)
                return
            #查询车辆具体型号
            model=query_carmodel(session,vehicleFrameNo)
            if model==0:
                model=queryAutoModelType(session,queryDMVehicleInfoConfirm_json['vehicleModel'])


            alldata['sy_insuranceEndTime']=sy_insuranceEndTime
            alldata['jq_insuranceEndTime']=jq_insuranceEndTime

            alldata['insurantInfo']=quick_resp['insurantInfo']
            alldata['vehicleTarget']=quick_resp['vehicleTarget']
            alldata['autoModelType']=quick_resp['autoModelType']
            alldata['DMVehicleInfo']=queryDMVehicleInfoConfirm_json
            alldata['model']=model
            alldata["insuranceType"]=insuranceType

            fee_resp=get_fee(session,alldata)

            if isinstance(fee_resp,dict):
                data=[]
                data.append(fee_resp['c01beginTime'])
                data.append(fee_resp['c01endTime'])
                data.append(fee_resp['vehicleSeats'])
                data.append(insureTypeGroupId)
                data.append(insureCarId)
                data.append("1")
                #log.info("平安开始入库 %s" % CPlateNo)
                #data=[开始时间,结束时间，座位数，组合id (insureTypeGroupId )，车辆id，公司id]
                soupDb(fee_resp['fee'],data)
                log.info("平安入库成功 %s " % CPlateNo )
                send_mq(client,CPlateNo,"","1","1",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)
            else:
                log.error(fee_resp)
                send_mq(client,CPlateNo,fee_resp,"2","1",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)
        else:
            if searchVin!="":
                sy_insuranceEndTime=endDate
                jq_insuranceEndTime=endDate
                session=user_data
                vehicleFrameNo=searchVin
                #请求车管所
                queryDMVehicleInfoConfirm_json=queryDMVehicleInfoConfirm(session,vehicleFrameNo,carMark="")

                if not isinstance(queryDMVehicleInfoConfirm_json,dict):
                    send_mq(client,CPlateNo,queryDMVehicleInfoConfirm_json,"2","1",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)
                    return
                #通过车架号查询车辆类型
                model=query_carmodel(session,vehicleFrameNo)
                #通过车辆编码查询车辆类型
                if model==0:
                    model=queryAutoModelType(session,queryDMVehicleInfoConfirm_json['vehicleModel'])
                #编码查询不到使用续保信息中的车辆名字进行查询
                if model==0 and renewal_data_dt.get("vehicleBrand","")!="":
                    model=queryAutoModelType(session,renewal_data_dt['vehicleBrand'])
                alldata['DMVehicleInfo']=queryDMVehicleInfoConfirm_json
                alldata['model']=model
                alldata['sy_insuranceEndTime']=sy_insuranceEndTime
                alldata['jq_insuranceEndTime']=jq_insuranceEndTime
                alldata["insuranceType"]=insuranceType
                fee_resp=get_fee(session,alldata)
                if isinstance(fee_resp,dict):
                    data=[]
                    data.append(fee_resp['c01beginTime'])
                    data.append(fee_resp['c01endTime'])
                    data.append(fee_resp['vehicleSeats'])
                    data.append(insureTypeGroupId)
                    data.append(insureCarId)
                    data.append("1")
                    #log.info("平安开始入库 %s" % CPlateNo)
                    soupDb(fee_resp['fee'],data)
                    log.info("平安入库成功 %s " % CPlateNo )
                    send_mq(client,CPlateNo,"","1","1",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)
                else:

                    if isinstance(fee_resp,list):
                        fee_resp=json.dumps(fee_resp,encoding=False)
                        log.error(fee_resp)
                    else:
                        log.error(fee_resp)
                        send_mq(client,CPlateNo,fee_resp,"2","1",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)
    except Exception,e:
        log.error(e)
        log.error(traceback.format_exc())
        send_mq(client,CPlateNo,"%s 未知错误" % CPlateNo,"2","1",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)




if __name__=="__main__":
    list = ['苏C680BA',
    '苏C337QC',
    '苏CR8678',
    '苏CW099J',
    '苏C736QA',
    '苏C672QB',
    '苏CY353X',
    '苏C165QD',
    '苏AB6U29',
    '苏JGZ393',
    '苏AN0Q83',
    '苏AN3Q63']

    #login=Login()
    #login_session=login.login()
    #U=is_entrance_renwal(login_session,"苏C-296QC")
    #print(U)
    for i in list:
        print i[:4]+"-"+i[4:]